package com.iamteer.mail;

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.junit.Test;

import com.sun.net.ssl.internal.ssl.Provider;

/**
 * 发送邮件
 * @author Chuck
 *
 */
public class AppSendMail {
	@Test
	public void testSend() throws Exception{
/*
		// 0. 邮件参数
		Properties prop = new Properties();
		prop.put("mail.transport.protocol", "smtp");
		prop.put("mail.smtp.host", "smtp.zoho.com");	//pop.zoho.com
		prop.put("mail.smtp.port", "465");
		prop.put("mail.smtp.auth", "true");
		prop.put("mail.debug", "true");
*/
        //设置SSL连接、邮件环境
        Security.addProvider(new Provider());  
        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";  
        Properties prop = new Properties();
        prop.setProperty("mail.smtp.host", "smtp.zoho.com");
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("mail.smtp.socketFactory.port", "465");
        prop.setProperty("mail.smtp.auth", "true");
        
		// 创建一个邮件会话
		Session session = Session.getDefaultInstance(prop);
		// 创建邮件体对象
		MimeMessage message = new MimeMessage(session);
		// 设置邮件体参数
		// 主题
		message.setSubject("我的第一封邮件");
		// 时间
		message.setSentDate(new Date());
		// 发件人
		message.setSender(new InternetAddress("learnjavamail@zoho.com"));
		// 收件人
		message.setRecipient(RecipientType.TO,  new InternetAddress("lch0821@foxmail.com"));
		// 内容
		message.setText("正文");
		message.saveChanges();
		
		// 发送
		Transport trans = session.getTransport();
		trans.connect("learnjavamail", "root123456");
		trans.sendMessage(message, message.getAllRecipients());
		trans.close();
	}
}
